<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>抽奖系统</title>
<style>
  body, html {
    height: 100%;
    margin: 0;
    font-family: Arial, sans-serif;
    display: flex;
    justify-content: center;
    align-items: center;
    background-color: #e6f7ff;
  }
  .wheel-container {
    position: relative;
    width: 300px;
    height: 300px;
    border-radius: 50%;
    display: flex;
    justify-content: center;
    align-items: center;
    color: white;
    font-size: 24px;
    font-weight: bold;
    transition: transform 6s ease-out;
  }
  .pointer {
    position: absolute;
    top: -20px;
    left: 50%;
    transform: translateX(-50%);
    width: 0;
    height: 0;
    border-left: 20px solid transparent;
    border-right: 20px solid transparent;
    border-bottom: 40px solid red;
  }
  button {
    margin-top: 20px;
    padding: 10px 20px;
    font-size: 16px;
    background-color: #ff6600;
    color: white;
    border: none;
    cursor: pointer;
    transition: background-color 0.3s;
  }
  button:hover {
    background-color: #ff3300;
  }
  /* 动画反馈 */
  button:active {
    transform: scale(0.9);
  }
  .prize-popup {
    display: none;
    position: fixed;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    background-color: rgba(0, 0, 0, 0.8);
    color: white;
    padding: 20px;
    border-radius: 10px;
    text-align: center;
    z-index: 1000;
  }
  .prize-popup.show {
    display: block;
  }
</style>
<script async src="https://www.googletagmanager.com/gtag/js?id=YOUR_TRACKING_ID"></script>
<script>
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', 'YOUR_TRACKING_ID');

const langPack = {
  zh: { title: "抽奖系统", start: "开始抽奖", close: "关闭" },
  en: { title: "Lucky Draw System", start: "Start Drawing", close: "Close" }
};

// 用户跟踪与防作弊机制
function getUserID() {
  let userID = localStorage.getItem('userID');
  if (!userID) {
    userID = 'user_' + Date.now();
    localStorage.setItem('userID', userID);
  }
  return userID;
}

function logWin(prizeName) {
  let history = JSON.parse(localStorage.getItem('winHistory')) || {};
  let userID = getUserID();
  if (!history[userID]) {
    history[userID] = [];
  }
  history[userID].push({ prize: prizeName, time: new Date().toISOString() });
  localStorage.setItem('winHistory', JSON.stringify(history));
}

function hasWonRecently(prizeName) {
  let history = JSON.parse(localStorage.getItem('winHistory')) || {};
  let userID = getUserID();
  let recentWins = history[userID]?.filter(win => new Date(win.time) > new Date(Date.now() - 24 * 60 * 60 * 1000));
  return recentWins?.some(win => win.prize === prizeName) || false;
}

// 随机打乱奖品数组
function shufflePrizes(prizes) {
  let currentIndex = prizes.length, temporaryValue, randomIndex;
  while (currentIndex !== 0) {
    randomIndex = Math.floor(Math.random() * currentIndex);
    currentIndex -= 1;
    [prizes[currentIndex], prizes[randomIndex]] = [prizes[randomIndex], prizes[currentIndex]];
  }
  return prizes;
}

// 加权随机选择函数
function weightedRandom(prizes) {
  let totalWeight = prizes.reduce((acc, prize) => acc + prize.weight, 0);
  let random = Math.random() * totalWeight;
  for (let i = 0; i < prizes.length; i++) {
    if (random < prizes[i].weight) return i;
    random -= prizes[i].weight;
  }
}

// 创建带有不同颜色的轮盘
function createWheel(prizes) {
  const colors = ['#ffcc00', '#ff9900', '#ff6600', '#ff3300', '#ff0000'];
  let gradientParts = [];
  prizes.forEach((_, index) => {
    gradientParts.push(`${colors[index]} ${(index * 100 / prizes.length)}%`);
    gradientParts.push(`${colors[(index + 1) % colors.length]} ${(index + 1) * 100 / prizes.length}%`);
  });
  document.querySelector('.wheel-container').style.background = `conic-gradient(${gradientParts.join(',')})`;
}

// 显示弹出窗口
function showPopup(prizeName) {
  const popup = document.getElementById('prizePopup');
  const popupPrizeText = document.getElementById('popupPrizeText');
  popupPrizeText.textContent = prizeName;
  popup.classList.add('show');
  trackEvent('draw_result', prizeName); // 跟踪抽奖结果
}

// 关闭弹出窗口
function closePopup() {
  document.getElementById('prizePopup').classList.remove('show');
}

// 跟踪抽奖事件
function trackEvent(action, label) {
  gtag('event', action, { event_category: 'LuckyDraw', event_label: label });
}

// 设置语言
function setLanguage(lang) {
  document.title = langPack[lang].title;
  
  // 确保 DOM 已经加载完成再设置文本内容
  if (document.readyState === 'complete') {
    document.querySelector('button').textContent = langPack[lang].start;
    document.querySelector('#prizePopup button').textContent = langPack[lang].close;
  } else {
    window.addEventListener('DOMContentLoaded', () => {
      document.querySelector('button').textContent = langPack[lang].start;
      document.querySelector('#prizePopup button').textContent = langPack[lang].close;
    });
  }
}

// 页面加载时初始化
window.onload = function() {
  let shuffledPrizes = shufflePrizes([...originalPrizes]);
  createWheel(shuffledPrizes);

  // 在页面加载完成后设置语言
  setLanguage(navigator.language.split('-')[0]);
};

// 将 isSpinning 作为全局变量声明并初始化为 false
let isSpinning = false;

const originalPrizes = [
  { name: '一等奖', weight: 1 },
  { name: '二等奖', weight: 2 },
  { name: '三等奖', weight: 3 },
  { name: '谢谢参与', weight: 10 },
  { name: '幸运奖', weight: 4 }
];

function startSpin() {
  if (isSpinning) return;

  const wheel = document.getElementById('wheel');
  const prizeText = document.getElementById('prizeText');

  // 确定最终奖品并计算其角度位置
  let selectedPrizeIndex = weightedRandom(originalPrizes);
  const selectedPrize = originalPrizes[selectedPrizeIndex].name;
  
  // 检查是否已经获得过该奖品
  if (hasWonRecently(selectedPrize)) {
    alert("您最近已经获得了这个奖品，请稍后再试！");
    return;
  }

  const prizeAngle = (360 / originalPrizes.length) * selectedPrizeIndex;

  // 设置旋转动画参数
  let rotations = 5 + Math.floor(Math.random() * 10); // 随机圈数

  isSpinning = true;
  prizeText.textContent = "正在抽奖...";

  // 快速旋转
  wheel.style.transform = `rotate(${rotations * 360}deg)`; // 先快速旋转多圈

  // 在接近结束时减速并定位到最终奖品位置
  setTimeout(() => {
    wheel.style.transition = `transform 3s ease-out`; // 减速效果
    wheel.style.transform = `rotate(${(rotations * 360) + prizeAngle}deg)`; // 停止在选定奖品位置

    setTimeout(() => {
      prizeText.textContent = selectedPrize;
      showPopup(selectedPrize); // 显示最终奖品
      logWin(selectedPrize); // 记录获奖历史
      isSpinning = false;
    }, 3000); // 等待减速动画完成
  }, 3000); // 等待快速旋转动画完成
}
</script>
</head>
<body>

<div style="display: flex; flex-direction: column; align-items: center;">
  <div class="wheel-container" id="wheel">
    <div class="pointer"></div>
    <div id="prizeText">点击开始</div>
  </div>
  <button onclick="startSpin()">开始抽奖</button>
  <div class="prize-popup" id="prizePopup">
    恭喜您获得了：<span id="popupPrizeText"></span><br>
    <button onclick="closePopup()">关闭</button>
  </div>
</div>

</body>
</html>